import Vue from 'vue'
import Vuex from 'vuex'
import * as api from './api.js'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        //数据库模式
        dbMode: "oracle",
        //申请资源是否成功
        applySuccess: false,
        //申请资源结果
        resource: {}
    },
    mutations: {
        changeDbMode(state, dbMode){
            state.dbMode = dbMode
        },
        setResource(state, resource){
            state.applySuccess = true
            state.resource = resource
        }
    },
    
    plugins: [
        createPersistedState({
          storage: window.sessionStorage,
          //不指定的，默认保存所有的state
        //   key: 'myStore', // 这个是存储在 sessionStorage 中的键名
        //   paths: ['dbMode','applySuccess', 'resource'], // 指定要持久化的状态路径
        }),
    ],
    actions: {
        async applyResource({commit, state}){
            const result = await api.applyResource(state.dbMode);
            if(result.success){
                commit('setResource', result.data)
            }
            return result;
        },
        executeSql({commit, state}, params){
            const {resource} = state;
            return api.executeSql({
                ...resource,
                pageNum: params.pageNum,
                pageSize: params.pageSize,
                sql: params.sql,
            });
        }
    }
});

export default store;